<script setup name="AsSelect">
  // 该组件用于搭配vxe-table使用
  // 写在最前面: options可不传, 默认使用vxe-column上绑定的filters
  // 以对el-select变量与事件进行透传(多数情况下组件可复用直接在组件上使用el-select的属性与事件即可, 如实现远程搜索)
  // <AsSelect remote :remote-method="handleRemoteMethod" :column="column" @change="handleFilterChangeEvent" />
  // function handleRemoteMethod(query) {
  //   console.log(query) // 请求接口修改options或修改vxe-column上绑定的filters
  // }
  // !注意插槽与 ref DOM 未作处理, 若业务复杂, 使用el-select自行处理
  import { ref, computed, watch } from 'vue'
  const props = defineProps({
    label: {
      type: String,
      default: 'label',
    },
    value: {
      type: String,
      default: 'value',
    },
    column: {
      type: Object,
      default: () => [],
    },
    iconWidth: {
      type: Number,
      default: 0,
    },
    teleported: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Array,
      default: () => [],
    },
    // 选择完后是否立即触发事件
    immediate: {
      type: Boolean,
      default: true,
    },
  })

  const asValue = ref(props.column)
  watch(
    () => props.column,
    (newValue, oldValue) => {
      asValue.value = newValue
    },
    {
      immediate: true,
      deep: true,
    }
  )

  const emit = defineEmits(['change'])

  const handleFilterChangeEvent = (params) => emit('change', params, props.immediate)

  const newOptions = computed(() => (props.options.length ? props.options : asValue.value.filters))

  const styleEl = computed(() => ({ display: 'inline-block', width: `calc(100% - ${props.iconWidth}px)` }))
</script>

<template>
  <el-select
    clearable
    filterable
    v-bind="$attrs"
    :style="styleEl"
    :teleported="teleported"
    v-model="asValue.filters[0].data"
    @change="handleFilterChangeEvent(asValue.filters[0])"
  >
    <el-option v-for="item in newOptions" :key="item.value" :label="item[label]" :value="item[value]" />
  </el-select>
</template>
